package com.example.main

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.RouterPath
import com.example.common.base.BaseActivity
import com.example.common.mvi.BaseMviActivity
import com.example.main.adapter.MainPageAdapter
import com.example.main.databinding.ActivityMainNavBinding
import com.example.main.tab.NormalTabView
import com.example.main.tab.RoundTabView
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener
@AndroidEntryPoint
@Route(path = RouterPath.PATH_MAIN_NAV_PAGE)
class MainActivityNav : BaseMviActivity<ActivityMainNavBinding>() {

    private lateinit var mNavController:NavigationController
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPageAdapter:MainPageAdapter
    private var needUserPermissions = arrayListOf(
        Manifest.permission.INTERNET,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.FOREGROUND_SERVICE
    )
    private var unGrantPermissions = arrayListOf<String>()
    private var hasUnGranted = false


    override fun initViews() {
        mNavController = mDatabinding.mainBottomNav.custom()
            .addItem(newTabItem(R.drawable.nav_home_normal, R.drawable.nav_home_checked, "首页"))
            .addItem(newTabItem(R.drawable.nav_movie_normal, R.drawable.nav_movie_checked, "放映厅"))
            .addItem(newRoundTabItem(R.drawable.nav_add_normal, R.drawable.nav_add_checked, "发布"))
            .addItem(newTabItem(R.drawable.nav_live_normal, R.drawable.nav_live_checked, "直播"))
            .addItem(newTabItem(R.drawable.nav_mine_normal, R.drawable.nav_mine_checked, "我的"))
            .build()
        //设置模块Fragment(推荐使用ARouter获取Fragment对象)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_HOME).navigation()as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE).navigation()as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_LIVE).navigation()as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MINE).navigation()as Fragment)

        mPageAdapter = MainPageAdapter(supportFragmentManager, fragments, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
        mDatabinding.mainViewPager.adapter = mPageAdapter
        mDatabinding.mainViewPager.offscreenPageLimit = 3 //设置离开屏幕的Fragment缓存大小

        //底部导航选中监听事件
        mNavController.addTabItemSelectedListener(object:OnTabItemSelectedListener{
            override fun onSelected(index: Int, old: Int) {
                when(index){
                    0,1-> mDatabinding.mainViewPager.currentItem = index
                    2->{
                        ARouter.getInstance().build(RouterPath.PATH_PUBLISH_PAGE).navigation()
                        mNavController.setSelect(old)
                    }
                    3->{
                        mDatabinding.mainViewPager.currentItem = index-1
                        //清理掉信息提示
                        mNavController.setHasMessage(3,false)
                        mNavController.setMessageNumber(3,0)
                    }
                    4->mDatabinding.mainViewPager.currentItem = index-1
                }
            }


            override fun onRepeat(index: Int) {
                if(index==2){
                    ARouter.getInstance().build(RouterPath.PATH_PUBLISH_PAGE).navigation()
                }
            }

        })
        //设置ViewPager的切换监听事件
        mDatabinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                Log.i("===============", "onPageScrolled: position: $position")
            }

            override fun onPageSelected(position: Int) {
                Log.i("===============", "onPageSelected: position: $position")
                when(position){
                    0, 1 -> mNavController.setSelect(position)
                    2, 3 -> mNavController.setSelect(position + 1)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                Log.i("===============", "onPageScrollStateChanged: state: $state")

            }
        })

        //设置直播间消息提示
        mNavController.setHasMessage(3, true)
        mNavController.setMessageNumber(3, 1)

        //检查应用权限
        mDatabinding.mainViewPager.postDelayed({
            autoRequestPermission()
        }, 2000)

    }

    private fun autoRequestPermission(): Boolean {
        //判断是否是Android6.0，动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //清理历史未授权的权限
            unGrantPermissions.clear()
            //检查用户是否同意过权限
            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED){
                    unGrantPermissions.add(it)
                }
            }

            //发起用户授权
            if (unGrantPermissions.size > 0){
                requestPermissions(unGrantPermissions.toTypedArray(), 100)
                return false
            }
        }
        return true

    }
    override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //检查是否还存在没有授权的权限
        if (requestCode == 100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermissions.forEach {
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }
        }
        //给出提示，让用户去设置中手动开启权限
        if (hasUnGranted){
            var builder = AlertDialog.Builder(this@MainActivityNav)
            builder.setTitle("权限提示")
            builder.setMessage("没有授权，请到应用详情中设置")
            builder.setPositiveButton("去设置"){ dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
                openAppDetailPage()
            }
            builder.setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
            }
        }
    }
    private fun openAppDetailPage(){
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this@MainActivityNav.startActivity(intent)
    }


    private fun newRoundTabItem(defaultResId: Int, checkedResId: Int, title: String): BaseTabItem {
        var roundTabView = RoundTabView(this@MainActivityNav).apply {
            initData(defaultResId, checkedResId, title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
        }
        return roundTabView
    }

    private fun newTabItem(defaultResId: Int, checkedResId: Int, title: String): BaseTabItem {
        var normalTabView = NormalTabView(this@MainActivityNav).apply {
            initData(defaultResId, checkedResId, title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
        }
        return normalTabView

    }
    override fun getLayoutId(): Int =R.layout.activity_main_nav

}